package com.link.base.base.fund.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.accnt.model.AcctAddress;
import com.link.base.base.fund.model.DealerAccount;
import com.link.base.base.fund.model.DealerTransactionDetail;
import com.link.base.base.fund.service.DealerAccountService;
import com.link.base.base.fund.service.DealerTransactionDetailService;
import com.link.base.base.system.model.Period;
import com.link.base.base.system.service.PeriodService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 处理交易明细，（查询，插入，生成对账单等）
 *
 * @author  姚润发
 * @date:   2016/12
 * @version 1.0
 */

@Controller
@RequestMapping("/link/dealerTransactionDetail")
public class DealerTransactionDetailController extends BasicController<DealerTransactionDetail> {

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private DealerTransactionDetailService dealerTransactionDetailService;

    @Resource
    private PeriodService periodService;

    @Resource
    private DealerAccountService dealerAccountService;

    @Override
    public BasicService<DealerTransactionDetail> getBasicService() throws Exception {
        return dealerTransactionDetailService;
    }

    @RequestMapping(value = "/queryDmsTransactionDetail")
    @ResponseBody
    public Map<String, Object> queryDmsTransactionDetail(@JsonParam QueryParams qps, @JsonParam DealerTransactionDetail entity, HttpSession session,
                                                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        CoreUser user = UserUtil.getUser();
        if (null == user.getAcctId()) {
            result.put("success", false);
            result.put("result", "无法获取当前用户经销商信息");
            return result;
        }
        qps.addFilter(new Filter("headId10123213131", "accntId", Filter.OP_EQUAL, String.valueOf(user.getAcctId())));
        return this.queryByExamplePage(qps, entity, session, request, response);
    }

    @Override
    @RequestMapping(value = "/insert")
    @ResponseBody
    public Map<String, Object> insert(@JsonParam DealerTransactionDetail entity, HttpSession session,
                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            beforInsert(entity, request);
            beforUpsert(entity, request);
            Long transactionDetailId = keyGenerateService.keyGenerate();
            entity.setId(transactionDetailId);
            String type = entity.getSourceType();
            //如果交易类型为空，则报错
            if (StringUtils.isNull(type)) {
                throw new ServiceException("FUND-016");
            }
            Long headId = entity.getHeadId();
            if (null == headId) {
                throw new ServiceException("PUBLIC-018");
            }
            dealerTransactionDetailService.insert(entity);
            DealerTransactionDetail newEntry = dealerTransactionDetailService.queryById(entity);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/listByAcctId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> listByAcctId(@JsonParam QueryParams qps, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<DealerTransactionDetail> list = null;
        try {
            qps.invokePreFilterAndSorter();
            qps.preDealSecurity(request);
            if (qps.getAttr1() != null && !"".equals(qps.getAttr1())) {
                qps.addFilter(new Filter("accntId", qps.getAttr1()));
            } else {
                throw new ServiceException("PUBLIC-026");
            }
            DealerTransactionDetail t = (DealerTransactionDetail) BasicModel.transformClass(DealerTransactionDetail.class, qps);
            beforQueryAllOrExample(t, request);
            beforQueryExample(t, request);
            list = dealerTransactionDetailService.queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<AcctAddress>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>根据期间id获取对交易明细</p>
     *
     * @author yrf
     * @param periodId
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("queryByPeriodId")
    @ResponseBody
    public Map<String, Object> queryByPeriodId(@RequestParam(required = true) Long periodId, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {

            CoreUser user = UserUtil.getUser();
            if (user == null || null == user.getAcctId()) {
                throw new ServiceException("FUND-021");
            }
            Period period = new Period();
            period.setId(periodId);
            period = periodService.queryById(period);
            if (period == null) {
                throw new ServiceException("FUND-022");
            }
            DealerTransactionDetail detail = new DealerTransactionDetail();
            period.setStartDate(period.getStartDate().substring(0, 19));
            period.setEndDate(period.getEndDate().substring(0, 19));
            detail.setAttr1(period.getStartDate());
            detail.setAttr2(period.getEndDate());
            Long accntId = user.getAcctId();
            detail.setAccntId(accntId);
            List<DealerTransactionDetail> list = dealerTransactionDetailService.queryByPeriod(detail);
            result.put("success", true);
            result.put("rows", list);
            result.put("period", period);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            return result;
        }
        return result;
    }

    /**
     * <p>返回打印对账单所需数据</p>
     *
     * @author yrf
     * @param periodId
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("getPeriodBillDetail")
    @ResponseBody
    public Map<String, Object> printBillByPeriodId(@RequestParam(required = true) Long periodId, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = queryByPeriodId(periodId, session, request, response);
        String suc = "success";
        if ((boolean) result.get(suc)) {
            CoreUser user = UserUtil.getUser();
            Long accntId = user.getAcctId();
            Period period = (Period) result.get("period");
            DealerAccount dealerAccount = new DealerAccount();
            dealerAccount.setAccntId(accntId);
            dealerAccount.setAttr1(period.getStartDate());
            dealerAccount.setAttr2(period.getEndDate());
            List<DealerAccount> dealerAccountList = dealerAccountService.queryByPeriod(dealerAccount);
            result.put("accountRows", dealerAccountList);
        }
        return result;
    }
}
